package com.mairuide.common.bill;

import com.mairuide._frame.utils.Testtrans;
import com.mairuide.casemanage.service.CaseManageService;
import com.mairuide.entity.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-06-26 17:20
 *  说明：该类是账单详情类，仅支持账单详情，自己需要啥条件自己去实体类加，一定要加上详细的注释。不要影响其他人。
 */
@Service
public class BillDetailService {
    @Autowired
    private CaseManageService caseManageService;
    @PersistenceContext
    private EntityManager entityManager;
    //查询话单详情  公共方法
    public PageResult search_detail(BillSearchParam dto) {
        String caseId = dto.getCaseId();
        String order = dto.getOrder();
        String sort = dto.getSort();
        String accountBody = dto.getAccountBody();
        String ct_beginTime = dto.getCt_beginTime();
        String ct_endTime = dto.getCt_endTime();
        String whichTable = caseManageService.getWhichTable(caseId);

        StringBuffer sb=new StringBuffer();
        sb.append(" SELECT a.* ,TRADE_DATE tradeDate,account_money accountMoney,surplus_money surplusMoney,institution_number institutionNumber,teller_number tellerNumber");
        sb.append(" from "+ whichTable +" a WHERE 1=1 ");
        if (StringUtils.isNotBlank(accountBody)){ // 交易主体名字
            sb.append(" and account_body = '" + accountBody +"' ") ;
        }
        //穿透分析需要的条件--------------
        if (StringUtils.isNotBlank(ct_beginTime)){ // 开始时间
            sb.append(" and  to_char(TRADE_DATE,'yyyy-mm-dd hh24:mi:ss') >= '" + ct_beginTime +"'");
        }
        if (StringUtils.isNotBlank(ct_beginTime)){ // 结束时间
            sb.append(" and  to_char(TRADE_DATE,'yyyy-mm-dd hh24:mi:ss') <= '" + ct_endTime +"'");
        }

        if (StringUtils.isNotBlank(sort)) {
            sb.append(" order by " + sort + " " + order);
        }else{
            sb.append(" ORDER BY TRADE_DATE DESC");
        }

        Query query = this.entityManager.createNativeQuery(sb.toString());
        //将查询结果集转为Map
        query.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(BillDetail.class));
        List<BillDetail> maps = query.getResultList();

        query.setFirstResult((dto.getPage()-1)*dto.getRows());
        query.setMaxResults(dto.getRows());
        //获取查询结果集
        List<BillDetail> list = query.getResultList();
        PageResult pageResult = new PageResult(Long.valueOf(maps.size()),list,null);
        return pageResult;
    }
}
